home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 117 / PC Guia 117.iso / Software / Produtividade / Software2 / Product4 / Setup.exe / drupal-4.6.0 / includes / file.inc < prev    next >
Encoding:
Text File  |  2005-03-31  |  16.5 KB  |  533 lines

  1. <?php
  2. /* $Id: file.inc,v 1.39 2005/03/31 21:18:08 dries Exp $ */
  3.  
  4. /**
  5.  * @file
  6.  * API for handling file uploads and server file management.
  7.  */
  8.  
  9. /**
  10.  * @defgroup file File interface
  11.  * @{
  12.  * Common file handling functions.
  13.  */
  14.  
  15. define('IS_WINDOWS', substr(PHP_OS, 0, 3) == 'WIN');
  16. define('FILE_DOWNLOADS_PUBLIC', 1);
  17. define('FILE_DOWNLOADS_PRIVATE', 2);
  18. define('FILE_CREATE_DIRECTORY', 1);
  19. define('FILE_MODIFY_PERMISSIONS', 2);
  20. define('FILE_DIRECTORY_TEMP', IS_WINDOWS ? 'c:\\windows\\temp' : '/tmp');
  21. define('FILE_EXISTS_RENAME', 0);
  22. define('FILE_EXISTS_REPLACE', 1);
  23. define('FILE_EXISTS_ERROR', 2);
  24.  
  25. /**
  26.  * Create the download path to a file.
  27.  *
  28.  * @param $path Path to the file to generate URL for
  29.  * @return URL pointing to the file
  30.  */
  31. function file_create_url($path) {
  32.   if (strpos($path, variable_get('file_directory_path', 'files')) !== false) {
  33.     $path = trim(substr($path, strlen(variable_get('file_directory_path', 'files'))), '\\/');
  34.   }
  35.   switch (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC)) {
  36.     case FILE_DOWNLOADS_PUBLIC:
  37.       return $GLOBALS['base_url'] .'/'. variable_get('file_directory_path', 'files') .'/'. str_replace('\\', '/', $path);
  38.     case FILE_DOWNLOADS_PRIVATE:
  39.       return url('system/files', 'file='. $path);
  40.   }
  41. }
  42.  
  43. /**
  44.  * Make sure the destination is a complete path and resides in the
  45.  * file system directory, if it is not prepend the
  46.  * file system directory.
  47.  *
  48.  * @param $dest Path to verify
  49.  * @return Path to file with file system directory appended if necessary.
  50.  */
  51. function file_create_path($dest = 0) {
  52.   if (!$dest) {
  53.     return variable_get('file_directory_path', 'files');
  54.   }
  55.  
  56.   $regex = (IS_WINDOWS ? '.?:\\\\' : '/');
  57.   if (!file_check_location($dest, variable_get('file_directory_path', 'files')) && !preg_match("|^$regex|", $dest)) {
  58.     return variable_get('file_directory_path', 'files') .'/'. trim($dest, '\\/');
  59.   }
  60.   else {
  61.     return $dest;
  62.   }
  63. }
  64.  
  65. /**
  66.  * Check that directory exists and is writable.
  67.  *
  68.  * @param $directory Path to extract and verify directory for.
  69.  * @param $mode Try to create the directory if it does not exist.
  70.  * @param $form_item Optional name for a field item to attach potential errors to.
  71.  * @return False when directory not found, or true when directory exists.
  72.  */
  73. function file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
  74.   $directory = rtrim($directory, '/\\');
  75.  
  76.   // Check if directory exists.
  77.   if (!is_dir($directory)) {
  78.     if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory, 0760)) {
  79.       drupal_set_message(t('Created directory %directory.', array('%directory' => theme('placeholder', $directory))));
  80.     }
  81.     else {
  82.       if ($form_item) {
  83.         form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => theme('placeholder', $directory))));
  84.       }
  85.       return false;
  86.     }
  87.   }
  88.  
  89.   // Check to see if the directory is writable.
  90.   if (!is_writable($directory)) {
  91.     if (($mode & FILE_MODIFY_PERMISSIONS) && @chmod($directory, 0760)) {
  92.       drupal_set_message(t('Modified permissions on directory %directory.', array('%directory' => theme('placeholder', $directory))));
  93.     }
  94.     else {
  95.       form_set_error($form_item, t('The directory %directory is not writable.', array('%directory' => theme('placeholder', $directory))));
  96.       return false;
  97.     }
  98.   }
  99.  
  100.   return true;
  101. }
  102.  
  103. /**
  104.  * Checks path to see if it is a directory, or a dir/file.
  105.  *
  106.  * @param $path
  107.  */
  108. function file_check_path(&$path) {
  109.   // Check if path is a directory.
  110.   if (file_check_directory($path)) {
  111.     return '';
  112.   }
  113.  
  114.   // Check if path is a possible dir/file.
  115.   $filename = basename($path);
  116.   $path = dirname($path);
  117.   if (file_check_directory($path)) {
  118.     return $filename;
  119.   }
  120.  
  121.   return false;
  122. }
  123.  
  124. /**
  125.  * Check if $source is a valid file upload.
  126.  *
  127.  * @param $source
  128.  */
  129. function file_check_upload($source) {
  130.   if (is_object($source)) {
  131.     if (is_file($source->filepath)) {
  132.       return $source;
  133.     }
  134.   }
  135.   elseif ($_FILES["edit"]["name"][$source] && is_uploaded_file($_FILES["edit"]["tmp_name"][$source])) {
  136.     $file = new StdClass();
  137.     $file->filename = trim(basename($_FILES["edit"]["name"][$source]), '.');
  138.     $file->filemime = $_FILES["edit"]["type"][$source];
  139.     $file->filepath = $_FILES["edit"]["tmp_name"][$source];
  140.     $file->error = $_FILES["edit"]["error"][$source];
  141.     $file->filesize = $_FILES["edit"]["size"][$source];
  142.     $file->source = $source;
  143.     return $file;
  144.   }
  145.   else {
  146.     // In case of previews return previous file object.
  147.     if (file_exists($_SESSION['file_uploads'][$source]->filepath)) {
  148.       return $_SESSION['file_uploads'][$source];
  149.     }
  150.   }
  151. }
  152.  
  153. /**
  154.  * Check if a file is really located inside $directory. Should be used to make
  155.  * sure a file specified is really located within the directory to prevent
  156.  * exploits.
  157.  *
  158.  * @code
  159.  *   // Returns false:
  160.  *   file_check_location('/www/example.com/files/../../../etc/passwd', '/www/example.com/files');
  161.  * @endcode
  162.  *
  163.  * @param $source A string set to the file to check.
  164.  * @param $directory A string where the file should be located.
  165.  * @return 0 for invalid path or the real path of the source.
  166.  */
  167. function file_check_location($source, $directory = 0) {
  168.   $source = realpath($source);
  169.   $directory = realpath($directory);
  170.   if ($directory && strpos($source, $directory) !== 0) {
  171.     return 0;
  172.   }
  173.   return $source;
  174. }
  175.  
  176. /**
  177.  * Copies a file to a new location. This is a powerful function that in many ways
  178.  * performs like an advanced version of copy().
  179.  * - Checks if $source and $dest are valid and readable/writable.
  180.  * - Performs a file copy if $source is not equal to $dest.
  181.  * - If file already exists in $dest either the call will error out, replace the
  182.  *   file or rename the file based on the $replace parameter.
  183.  *
  184.  * @param $source A string specifying the file location of the original file.
  185.  *   This parameter will contain the resulting destination filename in case of
  186.  *   success.
  187.  * @param $dest A string containing the directory $source should be copied to.
  188.  * @param $replace Replace behavior when the destination file already exists.
  189.  *   - FILE_EXISTS_REPLACE - Replace the existing file
  190.  *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique
  191.  *   - FILE_EXISTS_ERROR - Do nothing and return false.
  192.  * @return True for success, false for failure.
  193.  */
  194. function file_copy(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  195.   $dest = file_create_path($dest);
  196.  
  197.   $directory = $dest;
  198.   $basename = file_check_path($directory);
  199.  
  200.   // Make sure we at least have a valid directory.
  201.   if ($basename === false) {
  202.     drupal_set_message(t('File copy failed: no directory configured, or it could not be accessed.'), 'error');
  203.     return 0;
  204.   }
  205.  
  206.   // Process a file upload object.
  207.   if (is_object($source)) {
  208.     $file = $source;
  209.     $source = $file->filepath;
  210.     if (!$basename) {
  211.       $basename = $file->filename;
  212.     }
  213.   }
  214.  
  215.   $source = realpath($source);
  216.   if (!file_exists($source)) {
  217.     drupal_set_message(t('File copy failed: source file does not exist.'), 'error');
  218.     return 0;
  219.   }
  220.  
  221.   // If destination file is not specified then use filename of source file.
  222.   $basename = $basename ? $basename : basename($source);
  223.   $dest = $directory .'/'. $basename;
  224.  
  225.   // Make sure source and destination filenames are not the same, makes no sense
  226.   // to copy it if they are. In fact copying the file will most likely result in
  227.   // a 0 byte file. Which is bad. Real bad.
  228.   if ($source != realpath($dest)) {
  229.     if (file_exists($dest)) {
  230.       switch ($replace) {
  231.         case FILE_EXISTS_RENAME:
  232.           // Destination file already exists and we can't replace is so we try and
  233.           // and find a new filename.
  234.           if ($pos = strrpos($basename, '.')) {
  235.             $name = substr($basename, 0, $pos);
  236.             $ext = substr($basename, $pos);
  237.           }
  238.           else {
  239.             $name = $basename;
  240.           }
  241.  
  242.           $counter = 0;
  243.           do {
  244.             $dest = $directory .'/'. $name .'_'. $counter++ . $ext;
  245.           } while (file_exists($dest));
  246.           break;
  247.  
  248.         case FILE_EXISTS_ERROR:
  249.           drupal_set_message(t('File copy failed. File already exists.'), 'error');
  250.           return 0;
  251.  
  252.         case FILE_EXISTS_REPLACE:
  253.           // Leave $dest where it is for replace.
  254.       }
  255.     }
  256.  
  257.     if (!@copy($source, $dest)) {
  258.       drupal_set_message(t('File copy failed.'), 'error');
  259.       return 0;
  260.     }
  261.   }
  262.  
  263.   if (is_object($file)) {
  264.     $file->filename = $basename;
  265.     $file->filepath = $dest;
  266.     $source = $file;
  267.   }
  268.   else {
  269.     $source = $dest;
  270.   }
  271.  
  272.   return 1; // Everything went ok.
  273. }
  274.  
  275. /**
  276.  * Moves a file to a new location.
  277.  * - Checks if $source and $dest are valid and readable/writable.
  278.  * - Performs a file move if $source is not equal to $dest.
  279.  * - If file already exists in $dest either the call will error out, replace the
  280.  *   file or rename the file based on the $replace parameter.
  281.  *
  282.  * @param $source A string specifying the file location of the original file.
  283.  *   This parameter will contain the resulting destination filename in case of
  284.  *   success.
  285.  * @param $dest A string containing the directory $source should be copied to.
  286.  * @param $replace Replace behavior when the destination file already exists.
  287.  *   - FILE_EXISTS_REPLACE - Replace the existing file
  288.  *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique
  289.  *   - FILE_EXISTS_ERROR - Do nothing and return false.
  290.  * @return True for success, false for failure.
  291.  */
  292. function file_move(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  293.  
  294.   $path_original = is_object($source) ? $source->filepath : $source;
  295.  
  296.   if (file_copy($source, $dest, $replace)) {
  297.     $path_current = is_object($source) ? $source->filepath : $source;
  298.  
  299.     if ($path_original == $path_current || file_delete($path_original)) {
  300.       return 1;
  301.     }
  302.     drupal_set_message(t('Removing original file failed.'), 'error');
  303.   }
  304.   return 0;
  305. }
  306.  
  307. function file_create_filename($basename, $directory) {
  308.   $dest = $directory .'/'. $basename;
  309.  
  310.   if (file_exists($dest)) {
  311.     // Destination file already exists, generate an alternative.
  312.     if ($pos = strrpos($basename, '.')) {
  313.       $name = substr($basename, 0, $pos);
  314.       $ext = substr($basename, $pos);
  315.     }
  316.     else {
  317.       $name = $basename;
  318.     }
  319.  
  320.     $counter = 0;
  321.     do {
  322.       $dest = $directory .'/'. $name .'_'. $counter++ . $ext;
  323.     } while (file_exists($dest));
  324.   }
  325.  
  326.   return $dest;
  327. }
  328.  
  329. function file_delete($path) {
  330.   if (is_file($path)) {
  331.     return unlink($path);
  332.   }
  333. }
  334.  
  335. /**
  336.  * Saves a file upload to a new location. The source file is validated as a
  337.  * proper upload and handled as such.
  338.  *
  339.  * @param $source A string specifying the name of the upload field to save.
  340.  *   This parameter will contain the resulting destination filename in case of
  341.  *   success.
  342.  * @param $dest A string containing the directory $source should be copied to,
  343.  *   will use the temporary directory in case no other value is set.
  344.  * @param $replace A boolean, set to true if the destination should be replaced
  345.  *   when in use, but when false append a _X to the filename.
  346.  * @return An object containing file info or 0 in case of error.
  347.  */
  348. function file_save_upload($source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  349.   // Make sure $source exists in $_FILES.
  350.   if ($file = file_check_upload($source)) {
  351.     if (!$dest) {
  352.       $dest = variable_get('file_directory_temp', FILE_DIRECTORY_TEMP);
  353.       $temporary = 1;
  354.       if (is_file($file->filepath)) {
  355.         // If this file was uploaded by this user before replace the temporary copy.
  356.         $replace = 1;
  357.       }
  358.     }
  359.  
  360.     if (!user_access('bypass input data check') && !valid_input_data($file)) {
  361.       watchdog('security', t('Possible exploit abuse: invalid data.'), WATCHDOG_WARNING);
  362.       drupal_set_message(t('File upload failed: invalid data.'), 'error');
  363.       return 0;
  364.     }
  365.  
  366.     // Check for file upload errors.
  367.     switch ($file->error) {
  368.       case 0: // UPLOAD_ERR_OK
  369.         break;
  370.       case 1: // UPLOAD_ERR_INI_SIZE
  371.       case 2: // UPLOAD_ERR_FORM_SIZE
  372.         drupal_set_message(t('File upload failed: file size too big.'), 'error');
  373.         return 0;
  374.       case 3: // UPLOAD_ERR_PARTIAL
  375.       case 4: // UPLOAD_ERR_NO_FILE
  376.         drupal_set_message(t('File upload failed: incomplete upload.'), 'error');
  377.         return 0;
  378.       default: // Unknown error
  379.         drupal_set_message(t('File upload failed: unknown error.'), 'error');
  380.         return 0;
  381.     }
  382.  
  383.     unset($_SESSION['file_uploads'][is_object($source) ? $source->source : $source]);
  384.     if (file_move($file, $dest, $replace)) {
  385.       if ($temporary) {
  386.         $_SESSION['file_uploads'][is_object($source) ? $source->source : $source] = $file;
  387.       }
  388.       return $file;
  389.     }
  390.     return 0;
  391.   }
  392.   return 0;
  393. }
  394.  
  395. /**
  396.  * Save a string to the specified destination
  397.  *
  398.  * @param $data A string containing the contents of the file
  399.  * @param $dest A string containing the destination location
  400.  *
  401.  * @return A string containing the resulting filename or 0 on error
  402.  */
  403. function file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME) {
  404.   if (!user_access('bypass input data check') && !valid_input_data($data)) {
  405.     watchdog('security', t('Possible exploit abuse: invalid data.'), WATCHDOG_WARNING);
  406.     drupal_set_message(t('File upload failed: invalid data.'), 'error');
  407.     return 0;
  408.   }
  409.  
  410.   $temp = variable_get('file_directory_temp', FILE_DIRECTORY_TEMP);
  411.   $file = tempnam($temp, 'file');
  412.   if (!$fp = fopen($file, 'wb')) {
  413.     drupal_set_message(t('Unable to create file.'), 'error');
  414.     return 0;
  415.   }
  416.   fwrite($fp, $data);
  417.   fclose($fp);
  418.  
  419.   if (!file_move($file, $dest, $replace)) {
  420.     return 0;
  421.   }
  422.  
  423.   return $file;
  424. }
  425.  
  426. /**
  427.  * Transfer file using http to client. Pipes a file through Drupal to the
  428.  * client.
  429.  *
  430.  * @param $source File to transfer.
  431.  * @param $headers An array of http headers to send along with file.
  432.  */
  433. function file_transfer($source, $headers) {
  434.   ob_end_clean();
  435.  
  436.   foreach ($headers as $header) {
  437.     header($header);
  438.   }
  439.  
  440.   $source = file_create_path($source);
  441.  
  442.   // Transfer file in 1024 byte chunks to save memory usage.
  443.   $fd = fopen($source, 'rb');
  444.   while (!feof($fd)) {
  445.     print fread($fd, 1024);
  446.   }
  447.   fclose($fd);
  448.   exit();
  449. }
  450.  
  451. /**
  452.  * Call modules to find out if a file is accessible for a given user.
  453.  */
  454. function file_download() {
  455.   $file = $_GET['file'];
  456.   if (file_exists(file_create_path($file))) {
  457.     $list = module_list();
  458.     foreach ($list as $module) {
  459.       $headers = module_invoke($module, 'file_download', $file);
  460.       if ($headers === -1) {
  461.         drupal_access_denied();
  462.       }
  463.       elseif (is_array($headers)) {
  464.         file_transfer($file, $headers);
  465.       }
  466.     }
  467.   }
  468.   drupal_not_found();
  469. }
  470.  
  471. /**
  472.  * Finds all files that match a given mask in a given
  473.  * directory.
  474.  *
  475.  * @param $dir
  476.  *   The base directory for the scan.
  477.  * @param $mask
  478.  *   The regular expression of the files to find.
  479.  * @param $nomask
  480.  *   An array of files/directories to ignore.
  481.  * @param $callback
  482.  *   The callback function to call for each match.
  483.  * @param $recurse
  484.  *   When TRUE, the directory scan will recurse the entire tree
  485.  *   starting at the provided directory.
  486.  * @param $key
  487.  *   The key to be used for the returned array of files.  Possible
  488.  *   values are "filename", for the path starting with $dir,
  489.  *   "basename", for the basename of the file, and "name" for the name
  490.  *   of the file without an extension.
  491.  * @param $min_depth
  492.  *   Minimum depth of directories to return files from.
  493.  * @param $depth
  494.  *   Current depth of recursion. This parameter is only used internally and should not be passed.
  495.  *
  496.  * @return
  497.  *   An associative array (keyed on the provided key) of objects with
  498.  *   "path", "basename", and "name" members corresponding to the
  499.  *   matching files.
  500.  */
  501. function file_scan_directory($dir, $mask, $nomask = array('.', '..', 'CVS'), $callback = 0, $recurse = TRUE, $key = 'filename', $min_depth = 0, $depth = 0) {
  502.   $key = (in_array($key, array('filename', 'basename', 'name')) ? $key : 'filename');
  503.   $files = array();
  504.  
  505.   if (is_dir($dir) && $handle = opendir($dir)) {
  506.     while ($file = readdir($handle)) {
  507.       if (!in_array($file, $nomask)) {
  508.         if (is_dir("$dir/$file") && $recurse) {
  509.           $files = array_merge($files, file_scan_directory("$dir/$file", $mask, $nomask, $callback, $recurse, $key, $min_depth, $depth + 1));
  510.         }
  511.         elseif ($depth >= $min_depth && ereg($mask, $file)) {
  512.           $filename = "$dir/$file";
  513.           $basename = basename($file);
  514.           $name = substr($basename, 0, strrpos($basename, '.'));
  515.           $files[$$key] = new stdClass();
  516.           $files[$$key]->filename = $filename;
  517.           $files[$$key]->basename = $basename;
  518.           $files[$$key]->name = $name;
  519.           if ($callback) {
  520.             $callback($filename);
  521.           }
  522.         }
  523.       }
  524.     }
  525.  
  526.     closedir($handle);
  527.   }
  528.  
  529.   return $files;
  530. }
  531.  
  532. ?>
  533.